package com.android.download.activity

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.android.download.R
import com.android.download.adapter.MainAdapter
import com.android.download.entity.AppInfo
import com.android.lib.download.DownloadManager
import com.android.lib.download.entity.DownloadInfo
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), OnItemChildClickListener {

    private var mainAdapter: MainAdapter? = null
    private var viewModel: MainViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initData()
    }

    private fun initView() {
        recyclerView.layoutManager = LinearLayoutManager(this)
        val itemAnimator = recyclerView.itemAnimator
        if (itemAnimator is SimpleItemAnimator) {
            itemAnimator.supportsChangeAnimations = false
        }
        mainAdapter = MainAdapter(data = null, lifecycleOwner = this)
        mainAdapter?.addChildClickViewIds(R.id.tb_status, R.id.tb_cancel)
        mainAdapter?.setOnItemChildClickListener(this)
        recyclerView.adapter = mainAdapter
    }

    private fun initData() {
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        viewModel?.appListData?.observe(this, appListDataObserver)
        viewModel?.requestAppListData()
    }

    private val appListDataObserver: Observer<MutableList<AppInfo>> = Observer {
        mainAdapter?.setNewData(it)
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        adapter as MainAdapter
        val item = adapter.getItem(position)
        val downloadScope = DownloadManager.getDownloadTask(url = item.downloadUrl!!)
        val downloadInfo = downloadScope?.getDownloadInfo()
        downloadInfo ?: return
        when (view.id) {
            R.id.tb_status -> {
                when (downloadInfo.status) {
                    DownloadInfo.ERROR, DownloadInfo.PAUSE, DownloadInfo.NONE, DownloadInfo.WAITING -> downloadScope.download()
                    DownloadInfo.DOWNLOADING -> downloadScope.pause()
                }
            }
            R.id.tb_cancel -> {
                downloadScope.remove()
            }
        }
    }

}
